//
//  MTPaymentViewController.swift
//  MT
//
//  Created by ooops on 2020/3/11.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import RxCocoa
import Moya
import Result
import YPNavigationBarTransition
import MTCategory

extension MTPaymentViewController: MTNewPaymentFooterViewDelegate, MTMineWebViewControllerDelegate {
    func didTapAgreenButton(sender: UIButton) {
        isAgree = sender.isSelected
    }
    
    func didTapAgreenmentProtocol() {
        let c = MTMineWebViewController()
        c.selectValue = 3
        c.delegate = self
        self.navigationController?.pushViewController(c, animated: true)
    }
    
    func navigation() {
        
    }
}

extension MTPaymentViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    //MARK: UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // TODO:- Required Method
        return result.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MTNewPaymentItemCell.reuseIdentity(), for: indexPath) as! MTNewPaymentItemCell
        configureCell(cell: cell, forItemAt: indexPath)
        return cell
    }
    
    func configureCell(cell: MTNewPaymentItemCell, forItemAt indexPath: IndexPath) {
        let model = self.result[indexPath.item]
        cell.model = model
    }
    
//    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
//        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: MTNewPaymentFooterView.reuseIdentity(), for: indexPath) as! MTNewPaymentFooterView
//        view.delegate = self
//        return view
//    }
    //MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        removeLayer(indexPath: indexPath)
        let model = self.result[indexPath.item]
        self.currentSelectedModel = model
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        
    }
    
    private func removeLayer(indexPath: IndexPath) {
        
        for i in 0..<self.result.count {
            let model = self.result[i]
            if indexPath.item == i {
                model.isSelected = true
            } else {
                model.isSelected = false
            }
        }
        
        self.collectionView.reloadData()
        
    }
}

class MTPaymentViewController: BaseViewController {
    
    private var isAgree: Bool = false
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    var paymentViews: [MTPaymentItemView] = []
    /// 列表数据
    private var result: [MTPaymentResultModel] = []
    
    /// 当前选中的模型项
    private var currentSelectedModel: MTPaymentResultModel?
    
    private lazy var payProvider: MTProvider<MTPaymentAPI> = {
        let provider = MTProvider<MTPaymentAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    lazy var headerView: MTNewPaymentHeaderView = {
        let v = MTNewPaymentHeaderView()
        
        return v
    }()
    
    lazy var footerView: MTNewPaymentFooterView = {
        let v = MTNewPaymentFooterView()
        v.delegate = self
        return v
    }()
    
    lazy var rightBtn: UIButton = {
        let btn: UIButton = UIButton(type: .custom)
        btn.setTitle("联系客服", for: .normal)
        btn.titleLabel?.font = PingFangSCMediumFont(14)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.addTarget(self, action: #selector(_clickNavRightButton(sender:)), for: .touchUpInside)
        btn.sizeToFit()
        return btn
    }()
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        let inset: CGFloat = 12.0
        let itemWidth = (ScreenWidth - inset * 2 - 1 - 8 * 2) / 3
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth * 80 / 112)
        //flowLayout.headerReferenceSize = CGSize(width: ScreenWidth, height: 90)
//        flowLayout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
        flowLayout.footerReferenceSize = CGSize(width: ScreenWidth, height: 90)
        flowLayout.minimumLineSpacing = 10
        flowLayout.minimumInteritemSpacing = 8
        let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        cv.backgroundColor = .white
        cv.contentInset = UIEdgeInsets(top: 20, left: inset, bottom: inset, right: inset)
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
//        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTNewPaymentItemCell.self, forCellWithReuseIdentifier: MTNewPaymentItemCell.reuseIdentity())
        //cv.register(MTNewPaymentFooterView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: MTNewPaymentFooterView.reuseIdentity())
        return cv
    }()
    
    lazy var paymentBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("确认充值", for: .normal)
        btn.addTarget(self, action: #selector(wechatPay), for: .touchUpInside)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.layer.cornerRadius = 49 * 0.5
        btn.layer.masksToBounds = true
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        let item = UIBarButtonItem(customView: self.rightBtn)
        navigationItem.rightBarButtonItem = item
        self.title = "钻石充值"
        stupUI()
        makeConstraint()
        
        loadData()
        queryUserMoney()
    }
    
    private func stupUI() {
        view.addSubview(headerView)
        view.addSubview(collectionView)
        view.addSubview(footerView)
        view.addSubview(paymentBtn)
        
    }
    
    @objc private func _clickNavRightButton(sender: UIButton) {
        if let un = UserCenter.default.customerUserName {
            JMSGConversation.createSingleConversation(withUsername: un) { [weak self] (conversation, error) in
                guard let weakSelf = self else { return }
                if error == nil, conversation != nil {
                    if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                        nav.selectCategory()
                        
                        DispatchQueue.main.after(0.25) {
                            let conv: JMSGConversation = conversation as! JMSGConversation
                            nav.pushViewController(JCChatViewController(conversation: conv), animated: true)
                        }
                        
                        DispatchQueue.main.after(1, execute: {
                            weakSelf.navigationController?.popToRootViewController(animated: false)
                        })
                    }
                }
            }
        }
        
    }
    
    private func makeConstraint() {
        headerView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(NavigationBarHeight + StatusBarHeight)
            make.left.right.equalToSuperview()
            make.height.equalTo(90)
        }
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headerView.snp.bottom)
            make.bottom.equalTo(footerView.snp.top).offset(-20)
        }
        
        footerView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(paymentBtn.snp.top).offset(-50)
            make.height.equalTo(70)
        }
        
        paymentBtn.snp.makeConstraints { (make) in
            //make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-10 - ScreenBottomExtraOffset)
            make.left.equalToSuperview().offset(22)
            make.right.equalToSuperview().offset(-22)
            make.height.equalTo(49)
        }
    }
    
    
    private func loadData() {
        payProvider.rx.requestResult(.list).subscribe(onNext: { (result:Result<MTPaymentModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let model):
                if model.code == 200, let r = model.result {
                    self.result = r
                    DispatchQueue.main.async {
                        self.headerView.money = model.ticketAmount
                        self.collectionView.reloadData()
                    }
                }
            case .failure(_):
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
    private func queryUserMoney() {
        MTClubTool.queryUserMoney(provider: userProvider, complete: { [weak self](userMontyModel) in
            guard let weakSelf = self else { return }
            weakSelf.headerView.money = userMontyModel?.result
        }) { _ in
        }
    }
    
    override func refreshView() {
        loadData()
    }
    
    /// 微信支付
    @objc private func wechatPay() {
        if !isAgree {
            MBProgressHUD_JChat.show(text: "请先同意用户充值协议", view: self.view, 2)
            return
        }
        
        guard let id = currentSelectedModel?.id else {
            MBProgressHUD_JChat.show(text: "请先选择充值项目", view: self.view, 2)
            return
        }
        payProvider.rx.requestResult(.weChatPay(id: id)).subscribe(onNext: { (result:Result<WhchatPayModel, AnyError> , isCache:Bool) in
            switch result {
            case .success(let model):
                MTPayManager.manager.wxPay(pay_param: model, payResult: {[weak self] (payCode) in
                    self?.pay_Code(code: payCode)
                })
            case .failure(_):
                break
            }

        }).disposed(by: globalDisposedBag)
        
    }
    
    //MARK: 支付回调 code 处理
    func pay_Code(code: PayCode) {
        switch code {
        case .WXSUCESS:
            /// 支付成功
            MBProgressHUD_JChat.show(text: "支付成功", view: self.view, 2)
            queryUserMoney()
            break

        case .WXSCANCEL:
            MBProgressHUD_JChat.show(text: "支付取消", view: self.view, 2)
            break
        default:
            /// 支付失败
            MBProgressHUD_JChat.show(text: "支付失败", view: self.view, 2)
            break
        }
    }

}

extension MTPaymentViewController: MTPaymentItemViewDelegate {
    func didSelectedItem(item: MTPaymentItemView) {
        for i in 0..<self.paymentViews.count {
            /// 表示选中项, b保持选中状态
            if i == item.tag {
                
            } else {
                self.paymentViews[i].removeGLayer()
            }
            
        }
        /// 当前选中的模型
        self.currentSelectedModel = self.result[item.tag]
        
    }
}


extension MTPaymentViewController {
    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .showShadowImage]
    }
}
